//
//  OAuthController.swift
//  Weibo
//
//  Created by mac on 16/1/13.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthController: UIViewController {
    
    //属性的webView
    let webView = UIWebView()
    
    
    //MARK: 关闭页面
    @objc private func close() {
        //dismiss页面
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    override func loadView() {
        //将根视图 替换为 webView
        view = webView
        //设置代理
        webView.delegate = self
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //文字渲染颜色
        //只正对当前的导航视图控制器有效
        //        navigationController?.navigationBar.tintColor = UIColor.orangeColor()
        
        //一经设置 全局有效
        //        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        print(view)
        //设置导航条
        setNavBar()
        
        //加载授权页面
        loadOAuthPage()
    }
    
    private func setNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
         self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "记住密码", style: .Plain, target: self, action: "remember")
    }
    @objc private func remember(){
        let jsString = "document.getElementById('userId').value = 'leiggee@126.com', document.getElementById('passwd').value = 'oyonomg' "
            webView.stringByEvaluatingJavaScriptFromString(jsString)
    
    
    
    }
    
    //MARK: 加载授权页面
    
    private func loadOAuthPage() {
        //1. 获取url
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + "1957664129" + "&redirect_uri=" + "http://www.itcast.cn"
        //可选的url
        let url = NSURL(string: urlString)!
        //获取request
        let request = NSURLRequest(URL: url)
         webView.loadRequest(request)
        
    }
    private func loadtoken(code:String){
         let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        let parameters :[String : AnyObject] = ["client_id":client_id,"client_secret": client_secret, "grant_type":"authorization_code","code": code,"redirect_uri": redirect_uri]
        AFN.POST("https://api.weibo.com/oauth2/access_token", parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            guard let dic : [String : AnyObject] = result as? [String : AnyObject] else{
                print("数据格式错误")
                return
            }
            let  access_token = dic["access_token"] as! String
            let   uid = dic["uid"] as! String
              let account = AccountModel(dict: dic)
            
               self.loaduserInfo(account)
            }) { (_, error) -> Void in
                print(error)
        }
    
    
    
    }
    let client_id = "1957664129"
    let client_secret = "4801fd3a36bb4e1c87b9001b0e7f68aa"
    let redirect_uri = "http://www.itcast.cn"
    
    private func loaduserInfo(account:AccountModel){
          let urlString = "https://api.weibo.com/2/users/show.json"
          let afn = AFHTTPSessionManager()
        let parameters = ["access_token":account.access_token!,"uid":account.uid!]
         afn.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            SVProgressHUD.dismiss()
            if let dict  = result as? [String:AnyObject] {
                let name = dict["name"] as! String
                let avatar_large = dict["avatar_large"] as! String
                account.name = name
                account.avatar_large = avatar_large
               account.writetodefault()
            }
            
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.dismiss()
        }
    
    }
    
}


//swift中 这样写  是将一类的协议方法  写在一起 更加好阅读 和 维护
//同一类的协议方法  就被放在一个扩展中
extension OAuthController: UIWebViewDelegate {
    //显示 用户等待指示器
    func webViewDidStartLoad(webView: UIWebView) {
        //显示
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //隐藏
        SVProgressHUD.dismiss()
    }
    
    //非常重要的协议方法
    //通常协议方法 返回值 为 bool类型  返回 yes 通常控件可以正常运行
        func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
            //截取 url中 code授权码
            if let str = request.URL?.absoluteString {
               
                if str.containsString("code="){
                   
                  let query =  request.URL?.query
//                 let code = (reque as NSString).substringFromIndex(5)
                    let codeStr = "code="
                 let code = (query! as NSString).substringFromIndex(codeStr.characters.count)
                   loadtoken(code)
                    
                  return false
                }
                
                return true
            }
  
    

            return true
        }
}

